<?php
namespace Fox;
/**
 *
 * A query is a three piece container with :
 *  -> fields values
 *  -> framgements
 *  -> finder classname
 *  -> joins
 *  -> sorting
 *
 * @author Xavier VILAIN
 * @package Fox\QueryManager
 * @license
 */
class Query extends \Fox\Object\Versioned {

	/**
	 * Link to Query User Params
	 * @var string
	 */
	const LINK_PARAMS = "params";

	/**
	 * Update Query by Changing a Param
	 * @var string
	 */
	const CHANGE_PARAMS = "update-params";

	/**
	 * Link to a specific user param
	 * @var string
	 */
	const LINK_USER_PARAM = "userParam";

	/**
	 * Query Location Form
	 */
	public function location() {
		$targetUri = preg_replace("/\'/",'"',$this->target_uri);
		if(!empty($targetUri)) {

			$lParts = json_decode($targetUri,true);
			$mod = isset($lParts['mod']) ? $lParts['mod'] : null;
			$act = isset($lParts['act']) ? $lParts['act'] : null;
			$sac = !empty($lParts['sac']) ? $lParts['sac'] : null;

			return Generator::url($mod,$act,$sac,array('query' => true,
							'queryFields' => urlencode($this->jsonfields)));
		}
		return null;
	}

	/**
	 * Decode Query Fields and convert it to an array
	 * @param string Json Format
	 * @return array
	 */
	public static function fieldsToArray($fields) {
		$fields = preg_replace("/\'/",'"',urldecode($fields));
		$data = json_decode($fields,true);
		return isset($data['data']) ? $data['data'][0] : $data ;
	}
}
\Fox\Dao::infos(Query::className(),new \Fox\Object\Info('queries', \Fox\Databases::DB_APP));

\Fox\Object\Links::add(\Fox\Dao::link(Query\Param::className(),Query\Param::LINK_QUERY)
	->to(Query::className(), Query::LINK_PARAMS)
	->on('queryid')
	->versionFrom()
);

\Fox\Object\Links::add(\Fox\Dao::link(Query\Param::className(),Query\Param::LINK_USER_QUERY)
	->to(Query::className(), Query::LINK_USER_PARAM)
	->on('queryid')
	->oneToOne()
	->where('idusr = ?',array(\User::current()->getId()))
);